package cn.anline.amap.controller;

import act.db.ebean.EbeanDao;
import cn.anline.amap.entity.Ann_area;
import cn.anline.amap.pojo.area.DistrictsDTO;
import cn.anline.amap.pojo.area.ResponseDTO;
import cn.anline.amap.pojo.location.AddressComponentDTO;
import cn.anline.amap.pojo.location.RegeocodeDTO;
import com.google.gson.Gson;
import io.reactivex.Flowable;
import okhttp3.*;
import org.osgl.mvc.annotation.GetAction;

import javax.inject.Inject;
import java.io.IOException;
import java.util.function.Consumer;

public class Home {

    final String amapWebApiKey = "高德地图API key";
    @Inject
    EbeanDao<Long, Ann_area> areaEbeanDao;

    @GetAction("test")
    public Object test(){
        Ann_area ann_area = areaEbeanDao.findById(100000L);
        System.out.println(ann_area);
        return "测试接口";
    }
    @GetAction
    public Object areaList(){
//        请求之前，先要在数据库导入一份标准的县级数据库，数据购买地址：https://www.qqzeng.com/

        Iterable<Ann_area> ann_areaList = areaEbeanDao.findBy("level_type", 3);
        System.out.println("数据查询结果");
        System.out.println(ann_areaList.toString());
        ann_areaList.forEach(new Consumer<Ann_area>() {
            @Override
            public void accept(Ann_area ann_area) {
                Long adCode = ann_area.getId();
                System.out.println("Ad_Code: "+adCode);

                String url = "https://restapi.amap.com/v3/config/district?key="+amapWebApiKey+"&keywords="+adCode+"&subdistrict=3&extensions=base";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println("Okhttp请求失败");
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        System.out.println("Okhttp请求结束");
                        System.out.println("Okhttp请求状态");
                        System.out.println(response.isSuccessful());
                        if (response.isSuccessful()){
                            String res = response.body().string();

                            System.out.println("返回body 字符串");
                            System.out.println(res);
                            Gson gson = new Gson();
                            ResponseDTO responseDTO = gson.fromJson(res, ResponseDTO.class);
                            System.out.println("Gson 解析结果");
                            System.out.println(responseDTO.getInfocode());
                            System.out.println("Gson 解析结果 区域打印");
                            System.out.println(responseDTO.getDistricts());
                            if (responseDTO.getInfocode().equals(10000L)){
                                System.out.println("高德地图请求成功");
                                //返回了子区域数据
                                if (responseDTO.getDistricts() != null && responseDTO.getDistricts().size() > 0){
//                                        这里取第一个
                                    DistrictsDTO districtsDTO = responseDTO.getDistricts().get(0);
//                                    判断是不是返回了当前数据库下的请求结果
                                    if (districtsDTO.getAdcode().equals(adCode)){
                                        System.out.println("成功获取当前数据库下的县级<具体看请求的顶级级别，这里是县级请求>区域");
                                        System.out.println(districtsDTO.getName() + "(" + districtsDTO.getLevel() + ")");
//                                        判断是否是区县级
                                        if (districtsDTO.getLevel().equals("district")){
//                                            判断是否有下级 镇级 街道
                                            if (districtsDTO.getDistricts() != null && districtsDTO.getDistricts().size() > 0){
                                                System.out.println("成功获取了高德地图接口镇级/街道级数据");
                                                for (DistrictsDTO street : districtsDTO.getDistricts() ) {
                                                    if (street.getLevel().equals("street")){
                                                        System.out.println(street.getName() + "(" + street.getLevel() + ")");
                                                        System.out.println(street.getCenter());

                                                        String url1 = "https://restapi.amap.com/v3/geocode/regeo?key=" + amapWebApiKey + "&location=" + street.getCenter() + "&poitype=&radius=10&extensions=base&batch=false&roadlevel=0";
                                                        OkHttpClient client1 = new OkHttpClient();
                                                        Request request1 =  new Request.Builder()
                                                                .url(url1)
                                                                .build();

                                                        client1.newCall(request1)
                                                                .enqueue(new Callback() {
                                                                    @Override
                                                                    public void onFailure(Call call1, IOException e1) {
                                                                        System.out.println("OkHttp 1 请求失败");
                                                                        e1.printStackTrace();
                                                                    }

                                                                    @Override
                                                                    public void onResponse(Call call1, Response response1) throws IOException {
                                                                        System.out.println("OKHttp 1 请求结束");
                                                                        System.out.println("OKHttp 1 请求状态");
                                                                        System.out.println(response1.isSuccessful());
                                                                        if (response1.isSuccessful()){
                                                                            String res1 = response1.body().string();
                                                                            System.out.println("okhttp1 返回字符串");
                                                                            System.out.println(res1);
                                                                            Gson gson1 = new Gson();
                                                                            cn.anline.amap.pojo.location.ResponseDTO responseDTO1 = gson1.fromJson(res1, cn.anline.amap.pojo.location.ResponseDTO.class);
                                                                            System.out.println("Gson1 解析结果");
                                                                            System.out.println(responseDTO1.getInfocode());
                                                                            if (responseDTO1.getInfocode().equals(10000L)){
//                                                                                逆地址解析成功
                                                                                System.out.println("逆地址解析成功");
                                                                                RegeocodeDTO regeocodeDTO = responseDTO1.getRegeocode();
                                                                                AddressComponentDTO addressComponentDTO = regeocodeDTO.getAddressComponent();
                                                                                System.out.println(addressComponentDTO.getTownship() + addressComponentDTO.getTowncode());
                                                                                Ann_area ann_area1 = areaEbeanDao.findById(addressComponentDTO.getTowncode());
                                                                                if (ann_area1 == null){
                                                                                    Ann_area ann_area2 = new Ann_area();
                                                                                    ann_area2.setId(addressComponentDTO.getTowncode());
                                                                                    ann_area2.setName(addressComponentDTO.getTownship());
                                                                                    ann_area2.setMerger_name(ann_area .getMerger_name() +","+addressComponentDTO.getTownship());
                                                                                    String shortName = addressComponentDTO.getTownship();
                                                                                    ann_area2.setMerger_short_name(ann_area.getMerger_short_name() + "," + shortName);

                                                                                    String [] ll = street.getCenter().split(",");
                                                                                    if (ll.length == 2){
                                                                                        ann_area2.setLng(ll[0]);
                                                                                        ann_area2.setLat(ll[1]);
                                                                                    }
                                                                                    ann_area2.setPid(addressComponentDTO.getAdcode());
                                                                                    ann_area2.setCity_code(addressComponentDTO.getCitycode());
                                                                                    ann_area2.setLevel_type(4L);

                                                                                    Ann_area ann_area3 = areaEbeanDao.save(ann_area2);
                                                                                    if (ann_area3 != null){
                                                                                        System.out.println("新数据添加成功");
                                                                                        System.out.println(ann_area3.toString());
                                                                                    }else {
                                                                                        System.out.println("新数据添加失败");
                                                                                    }

                                                                                }else {
                                                                                    System.out.println("数据库已存在该towncode");
                                                                                    System.out.println(ann_area1.getId());
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                });
//                                                        OKhttp 2 代码结束
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }else {
                                System.out.println("高德地图请求失败");
                            }
                        }
                    }
                });
            }
        });
        return "我屮艸芔茻";
    }
}
